package com.cls.business.controller;

import com.cls.business.entity.*;
import com.cls.business.service.*;
import com.cls.business.vo.DeclareTopicVO;
import com.cls.common.annotation.ControllerEndpoint;
import com.cls.common.controller.BaseController;
import com.cls.common.entity.MyConstant;
import com.cls.common.entity.QueryRequest;
import com.cls.common.entity.ResponseVO;
import com.cls.common.enums.DictEnum;
import com.cls.common.exception.MyException;
import com.cls.common.utils.MyUtil;
import com.cls.common.utils.StringUtils;
import com.cls.system.entity.Expert;
import com.cls.system.entity.SysDict;
import com.cls.system.entity.SysFile;
import com.cls.system.entity.User;
import com.cls.system.service.ISysDictService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import com.cls.system.service.ISysFileService;

/**
 * 拟立项控制器
 *
 * @author wmm
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class PreItemController extends BaseController {

    private final IDeclareTopicService declareTopicService;

    private final ISysDictService sysDictService;

    private final ISysFileService sysFileService;

    private final ILogDeclareTopicService logDeclareTopicService;

    /**
     * 列表页面
     **/
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/preItem")
    public String preItemIndex(Model model) {
        List<SysDict> subjectType = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectType", subjectType);
        return MyUtil.view("business/preItem/preItem");
    }


    /**
     * 申请审核页面
     **/
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/preItem/examine/{declareTopicId}")
    public String examineView(@PathVariable Long declareTopicId, Model model) {
        DeclareTopic declareTopic = declareTopicService.getById(declareTopicId);
        model.addAttribute("declare", declareTopic);
        //查询附件

        Long applyFileId = declareTopic.getApplyFileId();
        SysFile applyFile;
        if (applyFileId != null) {
            applyFile = Optional.of(sysFileService.getById(applyFileId)).orElse(new SysFile());
        } else {
            applyFile = new SysFile();
        }

        Long preItemFileId = declareTopic.getPreItemFileId();
        SysFile preItemFile;
        if (preItemFileId != null) {
            preItemFile = Optional.of(sysFileService.getById(preItemFileId)).orElse(new SysFile());
        } else {
            preItemFile = new SysFile();
        }
        model.addAttribute("applyFile", applyFile);
        model.addAttribute("preItemFile", preItemFile);

        return MyUtil.view("business/preItem/examine");
    }


    @GetMapping("biz/preItem/list")
    @ResponseBody
    @RequiresPermissions("preItem:list")
    public ResponseVO preItemList(QueryRequest request, DeclareTopic declareTopic) {
        //必须查询拟立项后之后的的信息方可能展示
        List<String> codes = new ArrayList<>();
        codes.add(DictEnum.PRE_ITEM.getCode());
        codes.add(DictEnum.ITEM_NO_CHECK.getCode());
        codes.add(DictEnum.ITEM_CHECK_PASSED.getCode());
        codes.add(DictEnum.ITEM_CHECK_FAILED.getCode());
        codes.add(DictEnum.ITEM_PASSED.getCode());
        codes.add(DictEnum.ITEM_FAILED.getCode());
        codes.add(DictEnum.ITEM_CANCEL.getCode());
        declareTopic.setStatusTypeCodes(codes);
        //年度课题
        declareTopic.setTopicClassifyCode(DictEnum.ANNUAL.getCode());
        PageInfo<DeclareTopicVO> declareTopics = this.declareTopicService.findDeclareTopicsForEvaluation(request, declareTopic);
        return ResponseVO.success(declareTopics);
    }

    @ControllerEndpoint(operation = "审核", exceptionMessage = "审核失败")
    @PostMapping("biz/preItem/examine/{declareId}")
    @ResponseBody
    public ResponseVO defineLevel(@PathVariable Long declareId, Boolean isPass, String checkResult) {
        DeclareTopic declareTopic = new DeclareTopic();
        declareTopic.setDeclareId(declareId);
        declareTopic.setCheckResult(checkResult);

        LogDeclareTopic logDeclareTopic = new LogDeclareTopic();
        logDeclareTopic.setDeclareId(declareId);
        logDeclareTopic.setOperatorBy(getCurrentUser().getUserId());
        logDeclareTopic.setOperatorTime(new Date());
        logDeclareTopic.setReason(checkResult);
        logDeclareTopic.setOperatorTypeCode(DictEnum.OPERATOR_PRE_ITEM_CHECK.getCode());

        //审核通过
        if (isPass) {
            logDeclareTopic.setStatusTypeCode(DictEnum.ITEM_CHECK_PASSED.getCode());
            declareTopic.setStatusTypeCode(DictEnum.ITEM_CHECK_PASSED.getCode());
        } else {
            logDeclareTopic.setStatusTypeCode(DictEnum.ITEM_CHECK_FAILED.getCode());
            declareTopic.setStatusTypeCode(DictEnum.ITEM_CHECK_FAILED.getCode());
            declareTopic.setIsFinish(true);
        }

        logDeclareTopicService.createLogDeclareTopic(logDeclareTopic);
        declareTopicService.updateById(declareTopic);
        return ResponseVO.success();
    }


    /**
     * 拟立项申请提交
     *
     * @return
     */
    @ControllerEndpoint(operation = "拟立项申请提交", exceptionMessage = "拟立项申请提交失败")
    @PostMapping("biz/preItem/apply/{declareId}")
    @ResponseBody
    public ResponseVO apply(@PathVariable Long declareId, DeclareTopic declareTopic) {
        User currentUser = getCurrentUser();
        Long userId = currentUser.getUserId();
        DeclareTopic declareTopicOld = declareTopicService.getById(declareId);
        declareTopic.setTopicId(declareTopicOld.getTopicId());
        declareTopicService.preItemApply(declareTopic, userId);
        return ResponseVO.success();
    }


    @ControllerEndpoint(operation = "导出拟立项统计", exceptionMessage = "导出Excel失败")
    @GetMapping("biz/preItem/export/{period}")
    @RequiresPermissions("preItem:list")
    public void export(@PathVariable String period, HttpServletResponse response) {
        try {
            declareTopicService.exportPreItem(period, response);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("导出失败！");
        }
    }


    @ControllerEndpoint(operation = "导出拟立项申请书", exceptionMessage = "导出失败")
    @GetMapping("applicantInfo/exportPreItemApply/{declareId}")
//    @RequiresPermissions("preItem:applyExport")
    public void exportPreItemApply(@PathVariable("declareId") Long declareId, HttpServletResponse response) {
        User currentUser = getCurrentUser();
        this.declareTopicService.exportPreItemApply(currentUser.getUserId(), declareId, response);
    }


}
